import React, { Component } from "react";
import { GetCode } from "../../api/account";
import { Button, message } from "antd";
import { validate_email } from "../../utils/verification";
//定时器
let timer = null;
export default class Code extends Component {
  state = {
    username: this.props.username, //每次都会去获取
    code_button_disable: false,
    code_button_loading: false,
    code_button_text: "获取验证码",
    module: this.props.module,
  };
  //监听父组件传递过来的props
  componentWillReceiveProps({ username }) {
    this.setState({ username });
  }
  /**
   * 销毁
   */
  componentWillUnmount() {
    clearInterval(timer);
  }
  //获取验证码事件
  onCode = () => {
    const username = this.state.username;
    if (!username) {
      message.warning("邮箱不能为空", 1);
      return false;
    }
    if (!validate_email(username)) {
      message.warning("邮箱格式不正确", 1);
      return false;
    }
    const requresData = {
      username,
      module: this.state.module,
    };

    GetCode(requresData)
      .then((res) => {
        message.success(res.data.message);
        //倒计时执行
        this.countDowm();
      })
      .catch((error) => {
        this.setState({
          code_button_loading: false,
          code_button_text: "重新获取",
        });
      });
    this.setState({
      code_button_loading: true,
      code_button_text: "发送中",
    });
    return false;
  };
  /**
   * 倒计时409019683
   */
  countDowm = () => {
    //倒计时间
    let set = 60;
    //修改状态
    this.setState({
      code_button_disable: true,
      code_button_loading: false,
      code_button_text: `${set}s`,
    });
    timer = setInterval(() => {
      set--;
      if (set <= 0) {
        this.setState({
          code_button_disable: false,
          code_button_text: "重新获取",
        });

        return false;
      }
      this.setState({
        code_button_text: `${set}s`,
      });
    }, 1000);
    /**
     * setInterval  clearInerval  不间断定时器
     * setTimout    clearTimout   只执行一次
     */
  };
  render() {
    const { code_button_text, code_button_loading, code_button_disable } =
      this.state;

    return (
      <Button
        type="danger"
        disabled={code_button_disable}
        block
        loading={code_button_loading}
        onClick={this.onCode}
      >
        {code_button_text}
      </Button>
    );
  }
}
